﻿/**
 * Copyright (C) 2012 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGuice.Inject.Spi;

namespace NGuice.Inject.Internal
{
    //complete!
    internal sealed class ProviderToInternalFactoryAdapter<T> : IProvider<T>
    {
        private readonly InjectorImpl injector;

        private readonly InternalFactory<T> internalFactory;

        public ProviderToInternalFactoryAdapter(InjectorImpl injector, InternalFactory<T> internalFactory)
        {
            this.injector = injector;
            this.internalFactory = internalFactory;
        }

        public override string ToString()
        {
            return internalFactory.ToString();
        }

        public T Get()
        {
            Errors errors = new Errors();
            try
            {
                T t = injector.CallInContext(new InternalContextualCallable<T>(this.internalFactory, errors));
                errors.ThrowIfNewErrors(0);
                return t;
            }
            catch (ErrorsException e)
            {
                throw new ProvisionException(errors.Merge(e.Errors).Messages);
            }
        }

        object IProvider.Get()
        {
            return Get();
        }


        private class InternalContextualCallable<T> : ContextualCallable<T>
        {
            private InternalFactory<T> internalFactory;

            private Errors errors;

            internal InternalContextualCallable(InternalFactory<T> internalFactory, Errors errors)
            {
                this.internalFactory = internalFactory;
                this.errors = errors;
            }

            public T Call(InternalContext context)
            {
                Dependency dependency = context.Dependency;
                // Always pretend that we are a linked binding, to support
                // scoping implicit bindings.  If we are not actually a linked
                // binding, we'll fail properly elsewhere in the chain.
                return internalFactory.Get(errors, context, dependency, true);
            }
        }

    }
}
